//
//  ReportViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/9.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
/// 检查报告列表
class ReportViewController: BaseViewController {
    
    var selectClosure: ((_ vm: FamilyRowViewModel) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private var viewModel: FamilyViewModel? {
        didSet {
            tableView.reloadData()
        }
    }
    
    private var cardVm = BindCardViewModel(model: BindCardModel())

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 0, right: 0)
            tableView.backgroundColor = .background
            tableView.rowHeight = 138
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.tableFooterView = UIView()
            tableView.showsVerticalScrollIndicator = false
            tableView.showsHorizontalScrollIndicator = false
            tableView.register(FamilyViewCell.nibForCell(),
                               forCellReuseIdentifier: FamilyViewCell.reuseIdentifier())
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NotiName.loginSuccess, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}

private extension ReportViewController {
    func setupUI() {
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
    }
    
    func endRefresh() {
        tableView.mj_header?.endRefreshing()
    }
    
    @objc func addFamily() {
        let addVc = FamilyAddViewController(addType: .add)
        addVc.title = "添加成员"
        addVc.updateClosure = { [weak self] in
            self?.loadData()
        }
        navigationController?.pushViewController(addVc, animated: true)
    }
    
    @objc func loadData() {
        FamilyViewModel.getFamilyList(success: { models in
            self.endRefresh()
            self.viewModel = FamilyViewModel(models: models)
        }) { errorMsg in
            self.endRefresh()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc func loginSuccess() {
        tableView.mj_header?.beginRefreshing()
    }
}

extension ReportViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FamilyViewCell.reuseIdentifier(),
                                                 for: indexPath) as! FamilyViewCell
        if let vm = viewModel?.viewModel(for: indexPath) {
            cell.configure(with: vm, type: .report)
        }
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        switch vm.cardType {
        case .unbound:
            HUDTool.show(message: "请先去家庭成员绑卡")
        default:
            let webVc = ReportWebViewController(patientId: vm.patientId)
            webVc.title = "\(vm.name) - 检查报告"
            navigationController?.pushViewController(webVc, animated: true)
        }
    }
}

extension ReportViewController: FamilyViewCellDelegate {
    func familyViewCell(willEdit cell: FamilyViewCell) {
        
    }
    
    func familyViewCell(willBindCard cell: FamilyViewCell) {
        HUDTool.show(message: "请先去家庭成员绑卡")
    }
}

/**
extension ReportViewController {
    private func showAlert(_ vm: FamilyRowViewModel) {
        AlertTool.showAlert(self,
                            title: "绑卡后才能就诊、支付",
                            message: "是否想要绑定自费就诊卡/医保卡",
                            sureTitle: "绑卡",
                            cancelTitle: "暂不绑定",
                            type: .double,
                            sureHandler:
        { (_) in
            self.getBindCardList(vm)
        })
    }
    
    /// 查询是否有卡
    private func getBindCardList(_ vm: FamilyRowViewModel) {
//        activityView.startAnimating()
        BindCardViewModel.getBindCardList(patientId: vm.patientId, success: { model in
//            self.activityView.stopAnimating()
            self.cardVm = BindCardViewModel(model: model)
            
            switch self.cardVm.status {
            case .canBind: self.showSendCodeView(self.cardVm)
            case .changePhone: self.showChangePhoneView(self.cardVm)
            case .noCard: self.showSendCodeView(self.cardVm)
            }
            
        }) { errorMsg in
//            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 显示发送短信验证码view
    private func showSendCodeView(_ vm: BindCardViewModel) {
        let showView = UINib.loadViewFrom(BindCardMainView.self)
        showView.show(vm: vm)
        showView.delegate = self
    }
    
    /// 显示修改手机view
    private func showChangePhoneView(_ vm: BindCardViewModel) {
        AlertTool.showAlert(self, message: "您当前手机号\(vm.phone)，与医院预留手机号不一致", sureTitle: "申请修改", cancelTitle: "暂不绑定", type: .double, sureHandler: { (_) in
            self.pushChangephoneVc(vm)
        })
    }
    
    private func pushChangephoneVc(_ vm: BindCardViewModel) {
        let changePhoneVc = ChangePhoneController(patientId: vm.patientId)
        present(changePhoneVc, animated: true)
    }
}
 */

extension ReportViewController: BindCardMainViewDelegate {
    func didSendCodeMsg() {
        BindCardViewModel.sendSmsCode(phone: self.cardVm.phone) { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: "获取验证码失败")
            case .success:
                HUDTool.show(message: "验证码已发送")
            }
        }
    }
    
    func didEndEdit(textField: UITextField) {
        self.cardVm.msgCode = textField.text!
    }
    
    func didSureAddCard(msgCode: String) {
        switch cardVm.status {
        case .canBind:
            BindCardViewModel.bindCard(patientId: cardVm.patientId, phone: cardVm.phone, code: msgCode) { (errorMsg, code) in
                switch code {
                case .failure:
                    HUDTool.showError(message: errorMsg)
                case .success:
                    HUDTool.show(message: "绑卡成功")
                    self.tableView.mj_header?.beginRefreshing()
                }
            }
        case .noCard:
            BindCardViewModel.addCard(patientId: cardVm.patientId, code: msgCode) { (errorMsg, code) in
                switch code {
                case .failure:
                    HUDTool.showError(message: errorMsg)
                case .success:
                    HUDTool.show(message: "新增卡片成功")
                    self.tableView.mj_header?.beginRefreshing()
                }
            }
        default: break
        }
    }
}

